import { createRouter, createWebHistory } from 'vue-router';

// 导入你的组件
import About from '@/views/About.vue';
import Home from '@/views/Home.vue'
import Login from "@/views/Login.vue";
import {useUserStore} from "@/stores/userStore.js";
import {isEmpty} from "element-plus/es/utils/index";
import Welcome from "@/views/Welcome.vue";
import Tasks from "@/views/Tasks.vue";
import Team from "@/views/Team.vue";
import Doc from "@/views/Document.vue"
import Overview from "@/views/Overview.vue";
import Tracking from "@/views/Tracking.vue";
import Settings from "@/views/Settings.vue";

// 定义路由
const routes = [
    {
        path: '/', // 路由路径
        name: 'Home', // 路由名称
        component: Home, // 对应的组件
        meta: { title: 'Home', requiresAuth: true }, // 添加 meta 信息
        redirect: '/welcome',
        children: [
            {
                path: 'welcome',
                name: 'Welcome',
                component: Welcome,
            },
            {
                path: 'overview',
                name: 'Overview',
                component: Overview,
            },
            {
                path: 'tasks',
                name: 'Tasks',
                component: Tasks,
            },
            {
                path: 'team',
                name: 'Team',
                component: Team,
            },
            {
                path: 'document',
                name: 'Document',
                component: Doc,
            },
            {
                path: 'tracking',
                name: 'Tracking',
                component: Tracking,
            },
            {
                path: 'settings',
                name: 'Settings',
                component: Settings,
            }
        ]
    },
    {
        path: '/login',
        name: 'Login',
        component: Login,
        meta: { title: 'Login', requiresAuth: false }, // 添加 meta 信息
    },
    {
        path: '/about',
        name: 'About',
        component: About,
        meta: { title: 'About', requiresAuth: false }, // 添加 meta 信息
    },
];

// 创建路由实例
const router = createRouter({
    history: createWebHistory(), // 使用 HTML5 的 history 模式
    routes, // 传入路由配置
});

// 全局前置守卫
router.beforeEach((to, from, next) => {
    const userStore = useUserStore()

    userStore.initialize()  // 初始化

    const token  = userStore.currentToken; // 获取登录token
    const requiresAuth = to.meta.requiresAuth;  // 检查目标路由是否需要登录

    if(requiresAuth && isEmpty(token)) {
        // 如果需要登录但用户未登录，则重定向到登录页面
        next({name: 'Login'});
    } else if(to.name === "Login" && token) {
        // 如果用户已登录但访问的是登录页面，则重定向到首页或其他页面
        next({name: 'Home'});
    } else {
        next()
    }
})

export default router;